﻿using System;
using System.Collections.Generic;
using System.Text;
using Graffiti.Core;
using System.Collections.Specialized;
using System.Web;
using System.Text.RegularExpressions;

namespace GraffitiExtras.Plugins.CommunityCredit
{
    public class CommunityCredit : GraffitiEvent
    {
        #region Fields

        public string FIRSTNAME;
        public string LASTNAME;
        public string EMAIL;

        #endregion

        #region EditableForm members

        public override string Name
        {
            get
            {
                return "Community Credit";
            }
        }

        public override string Description
        {
            get
            {
                return "<a href=\"http://www.community-credit.com\">Community Credit</a> " +
                    "plug-in for Graffiti by <a href=\"http://nayyeri.net\">" +
                    "Keyvan Nayyeri</a>.";
            }
        }

        public override bool IsEditable
        {
            get
            {
                return true;
            }
        }

        protected override NameValueCollection DataAsNameValueCollection()
        {
            NameValueCollection nvc = base.DataAsNameValueCollection();
            nvc["FIRSTNAME"] = FIRSTNAME;
            nvc["LASTNAME"] = LASTNAME;
            nvc["EMAIL"] = EMAIL;

            return nvc;
        }

        public override StatusType SetValues(HttpContext context, NameValueCollection nvc)
        {
            base.SetValues(context, nvc);

            FIRSTNAME = nvc["FIRSTNAME"];
            LASTNAME = nvc["LASTNAME"];
            EMAIL = nvc["EMAIL"];

            return StatusType.Success;
        }

        protected override FormElementCollection AddFormElements()
        {
            FormElementCollection fec = new FormElementCollection();

            fec.Add(new TextFormElement("FIRSTNAME", "First Name", "Your first name"));
            fec.Add(new TextFormElement("LASTNAME", "Last Name", "Your last name"));
            fec.Add(new TextFormElement("EMAIL", "Email",
                "The email address that you used to register on Community-Credit.Com"));

            return fec;
        }

        #endregion

        #region GraffitiEvent members

        public override void Init(GraffitiApplication ga)
        {
            ga.AfterInsert += new DataObjectEventHandler(ga_AfterInsert);
        }

        void ga_AfterInsert(DataBuddyBase dataObject, EventArgs e)
        {
            Post post = dataObject as Post;

            try
            {
                if (post != null)
                {
                    CommunityCreditService service = new CommunityCreditService();

                    Earner earner = new Earner(FIRSTNAME, LASTNAME, EMAIL);

                    PointCategory category = new PointCategory("Blog");

                    string pattern = @"(?<http>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)";
                    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
                    MatchCollection matches = regex.Matches(post.Body);
                    int linksCount = matches.Count;

                    List<string> suggestedTags = new List<string>();
                    if (post.TagList.ToLower().Contains("article"))
                        suggestedTags.Add("Article");
                    if (post.TagList.ToLower().Contains("snippet"))
                        suggestedTags.Add("Snippet");
                    if (post.TagList.ToLower().Contains("example"))
                        suggestedTags.Add("Example");
                    if (post.TagList.ToLower().Contains("tool"))
                        suggestedTags.Add("Tool");
                    if (post.TagList.ToLower().Contains("review"))
                        suggestedTags.Add("Review");

                    string taskDescriptionPattern =
                        "[Graffiti][Title: {0}][Length: {1}][Links Count: {2}][Suggested Tags: {3}][/Graffiti]";
                    string taskDescription = string.Format(taskDescriptionPattern,
                        post.Title, post.Body.Length.ToString(), linksCount.ToString(),
                        string.Join(", ", suggestedTags.ToArray()));

                    Task task = new Task(taskDescription, new Macros().FullUrl(post.Url), category);

                    service.AddCommunityCredit(earner, task);

                    Log.Info("Community Credit Plug-In", string.Format
                        ("Credit for post \"{0}\" is added successfully. The description for task was \"{1}\".",
                        post.Title, taskDescription));
                }
            }
            catch (Exception ex)
            {
                Log.Error("Community Credit Plug-In", ex.Message + ex.StackTrace);
            }
        }

        #endregion
    }
}
